package com.example.healthmanagement.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.healthmanagement.R;
import com.example.healthmanagement.bean.SportRecord;
import com.example.healthmanagement.util.MySqliteOpenHelper;
import com.example.healthmanagement.util.SPUtils;
import com.example.healthmanagement.view.SportStepView;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 运动记录
 */
public class SportRecordActivity extends AppCompatActivity {
    MySqliteOpenHelper helper = null;

    private SensorManager sensorManager;

    private Sensor accelerometerSensor;

    private TextView stepTv;

    private int step = 0;

    private SportStepView sportStepCount;

    private boolean isRuning = false;

    private boolean motiveState = true;

    private  double lastSpeed = 0;

    private Integer userId;


    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat sf1 = new SimpleDateFormat("HH:mm:ss");

    private SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            double speed = Math.sqrt(event.values[0] * event.values[0] + event.values[1] * event.values[1] + event.values[2] * event.values[2]);

            if (motiveState){
                if (speed >= lastSpeed){
                    lastSpeed = speed;
                }else {
                    if (Math.abs(speed - lastSpeed) > 2){
                        motiveState = false;
                        lastSpeed = speed;
                    }
                }
            }

            if (!motiveState){
                if (speed <= lastSpeed){
                    lastSpeed = speed;
                }else {
                    if (Math.abs(speed - lastSpeed) > 2) {
                        motiveState = true;
                        lastSpeed = speed;
                        if (isRuning) {
                            step++;
                            sportStepCount.setCurrentCount(5000,step);
                        }
                    }
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport_record);

        helper = new MySqliteOpenHelper(this);
        stepTv = findViewById(R.id.sportStepCountInfo);
        sportStepCount = findViewById(R.id.sportStepCount);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_UI);
        userId = (Integer) SPUtils.get(SportRecordActivity.this,SPUtils.USER_ID,0);
    }

    public void onAction(View view) {
        Button button = (Button) view;
        if ("开始".equals(button.getText().toString())){
            button.setText("停止");
            stepTv.setText("正在记步...");
            isRuning = true;
        }else {
            button.setText("开始");
            stepTv.setText("未开始");
            isRuning = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sensorManager.unregisterListener(sensorEventListener);
    }

    //打卡
    public void card(View v){
        AlertDialog.Builder builder = new AlertDialog.Builder(SportRecordActivity.this);
        View view = getLayoutInflater().inflate(R.layout.dialog_sport, null);
        final EditText editText = (EditText) view.findViewById(R.id.et_value);//拿到弹窗输入框
        builder.setTitle("打卡")
                .setView(view)//设置自定义布局
                //确定按钮的点击事件
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String remarkValue = editText.getText().toString().trim();
                        SQLiteDatabase db = helper.getWritableDatabase();
                        SportRecord sportRecord = null;
                        //查询是否存在
                        String sql = "select * from sport_record where date = ? and userId = "+userId;
                        Cursor cursor = db.rawQuery(sql, new String[]{sf.format(new Date())});
                        if (cursor != null && cursor.getColumnCount() > 0) {
                            while (cursor.moveToNext()) {
                                Integer dbId = cursor.getInt(0);
                                Integer dbUserId = cursor.getInt(1);
                                Integer step = cursor.getInt(2);
                                String remark = cursor.getString(3);
                                String date = cursor.getString(4);
                                String time = cursor.getString(5);
                                sportRecord = new SportRecord(dbId, dbUserId, step,remark, date, time);
                            }
                        }
                        if (sportRecord != null) {//存在 修改
                            Toast.makeText(SportRecordActivity.this, "你今天已经打卡，请明天再来", Toast.LENGTH_SHORT).show();
                        } else {//新增
                            String insertSql = "insert into sport_record (userId,step,remark,date,time)values(?,?,?,?,?);";
                            db.execSQL(insertSql, new Object[]{userId,step,remarkValue, sf.format(new Date()), sf1.format(new Date())});
                            db.close();
                            Toast.makeText(SportRecordActivity.this, "打卡成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                //设置取消按钮的点击事件
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                //弹窗消失的监听事件
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                    }
                })
                .create();
        builder.show();
    }


    public void sport(View view){
        Intent intent = new Intent(SportRecordActivity.this,SportRecordListActivity.class);
        startActivity(intent);
    }


    public void back(View view) {
        finish();
    }
}
